class EventsController < ApplicationController
  before_filter :find_event,      :only => [:show, :edit, :update, :destroy]
  before_filter :require_login,   :only => [:create, :edit, :new, :update, :destroy]
  
  # GET, events_url
  def index
    @events = (Event.find :all, :order => 'start_time')
  end
  
  # GET, event_url
  def show
    respond_to do |a|
      a.html {}
      a.xml { render :xml => @event.to_xml( :except => [:updated_at, :created_at, :series_id] )}
    end
  end
  
  # GET, new_event_url
  def new
    @series = Series.find(params[:series_id]) if params[:series_id]
    @event = Event.new
  end
  
  # POST, events_url
  def create
    if (params[:series_id])
      @series = Series.find params[:series_id]
      @event = @series.events.build(params[:event])
      @event.save!
      redirect_to series_event_url(@series, @event)
    else
      @event = Event.new(params[:event])
      @event.save!
      redirect_to events_url
    end
  rescue ActiveRecord::RecordInvalid
    flash[:error] = 'Nice one, jackass.'
    render :action => 'new'
  end
  
  # GET, edit_event_url
  def edit
    redirect_to event_url if @event.end_time < Time.now
  end
  
  # PUT, event_url
  def update
    if (params[:series_id])
      @series = Series.find params[:series_id]
      @event = @series.events.build(params[:event])
      @event.update_attributes!
      redirect_to series_event_url(@series, @event)
    else
      @event.update_attributes!(params[:event])
      redirect_to event_url
    end
    #/@event.update_attributes!(params[:event])
    #redirect_to event_url
    
  rescue ActiveRecord::RecordInvalid
    flash[:error] = 'Nice one, jackass'
    render :action => 'edit'
  end
  
  # DELETE, event_url
  def destroy
    @event.destroy
    flash[:alert] = 'The event has been deleted'
    redirect_to events_url
  end
  
protected
  def require_login
    if !logged_in?
      flash[:error] = 'You must be logged in to do that'
      redirect_to new_session_url
    end
  end
  
  def find_event
    @event = Event.find params[:id]
    redirect_to one_series_url(@event) if @event.is_a?(Series)
  end
end
